pathbench.models
Here one can use pytorch modules as custom MIL aggregator models instead of the ones included in slideflow. The construted modules can be imported into the benchmark.py script to be used in the benchmarking process.
- class pathbench.models.aggregators.air_mil(n_feats: int, n_out: int, z_dim: int = 256, initial_k: int = 20, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleAdaptive Instance Ranking MIL (AIR-MIL), which is a learnable top-k MIL model. First, the model computes attention weights for each instance and selects the top-k instances based on these weights. The model then computes the weighted mean of the top-k instances and passes the result through a classifier. The model also includes a learnable parameter k that determines the number of instances to select. Useful for problems where the number of relevant intances is unknown.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - initial_k: Initial value of the learnable parameter k - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - calculate_attention: Calculate the attention weights for each instance - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': 'Adaptive Instance Ranking MIL (AIR-MIL), which is a learnable top-k MIL model. First, the model computes\n attention weights for each instance and selects the top-k instances based on these weights. The model then\n computes the weighted mean of the top-k instances and passes the result through a classifier. The model also\n includes a learnable parameter k that determines the number of instances to select. Useful for problems\n where the number of relevant intances is unknown.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - initial_k: Initial value of the learnable parameter k\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - calculate_attention: Calculate the attention weights for each instance\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function air_mil.__init__>, '_initialize_weights': <function air_mil._initialize_weights>, 'forward': <function air_mil.forward>, 'calculate_attention': <function air_mil.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, initial_k: int = 20, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, return_attention=False)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- pathbench.models.aggregators.build_encoder(n_feats: int, z_dim: int, encoder_layers: int, activation_function: str, dropout_p: float = 0.1, use_batchnorm: bool = True)[source]
Builds an encoder with a specified number of layers and activation functions.
Args: - n_feats: Number of input features - z_dim: Dimension of the latent space - encoder_layers: Number of layers in the encoder - activation_function: Activation function to use in the encoder - dropout_p: Dropout probability - use_batchnorm: Whether to use batch normalization in the encoder
Returns: - encoder: Encoder network
- class pathbench.models.aggregators.clam_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleClusering-constrained Attention MIL (CLAM-MIL) model. The model uses a learnable attention mechanism to aggregate instance embeddings into slide-level representations. The model also includes a clustering module to predict instance-level cluster assignments. For each output class the model has a separate attention mechanism and classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - cluster_patches: Cluster patches into clusters - calculate_attention: Calculate the attention weights for each instance - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag - attention_weights: Attention weights for each instance (optional)
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Clusering-constrained Attention MIL (CLAM-MIL) model. The model uses a learnable attention mechanism to\n aggregate instance embeddings into slide-level representations. The model also includes a clustering module\n to predict instance-level cluster assignments. For each output class the model has a separate attention\n mechanism and classifier. \n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - cluster_patches: Cluster patches into clusters\n - calculate_attention: Calculate the attention weights for each instance\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n - attention_weights: Attention weights for each instance (optional)\n ', '__init__': <function clam_mil.__init__>, '_initialize_weights': <function clam_mil._initialize_weights>, 'forward': <function clam_mil.forward>, 'cluster_patches': <function clam_mil.cluster_patches>, 'calculate_attention': <function clam_mil.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, return_attention=False)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.clam_mil_mb(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, n_branches: int = 3, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleCLAM-MIL model with multiple branches, each with its own attention mechanism and classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - n_branches: Number of branches - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - calculate_attention: Calculate the attention weights for each instance - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for instances in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n CLAM-MIL model with multiple branches, each with its own attention mechanism and classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - n_branches: Number of branches\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - calculate_attention: Calculate the attention weights for each instance\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for instances in the bag\n ', '__init__': <function clam_mil_mb.__init__>, '_initialize_weights': <function clam_mil_mb._initialize_weights>, 'forward': <function clam_mil_mb.forward>, 'calculate_attention': <function clam_mil_mb.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, n_branches: int = 3, activation_function='ReLU', encoder_layers=1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, return_attention=False)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.deepset_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleDeep Sets MIL model. The model uses three fully connected layers to process the instance embeddings: the encoder network, phi and rho. The phi network processes the instance embeddings, which are summed and then the rho network classies the summed embeddings.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': ' Deep Sets MIL model. The model uses three fully connected layers to process the instance embeddings:\n the encoder network, phi and rho. The phi network processes the instance embeddings, which are summed and then the rho network\n classies the summed embeddings. \n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n \n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function deepset_mil.__init__>, '_initialize_weights': <function deepset_mil._initialize_weights>, 'forward': <function deepset_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.distributionpooling_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleDistribution Pooling MIL model. The model computes the mean and variance of the instance embeddings and concatenates these statistics. The model then passes the concatenated embeddings through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Distribution Pooling MIL model. The model computes the mean and variance of the instance embeddings and\n concatenates these statistics. The model then passes the concatenated embeddings through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function distributionpooling_mil.__init__>, '_initialize_weights': <function distributionpooling_mil._initialize_weights>, 'forward': <function distributionpooling_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.dsmil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleDual-stream MIL model. The model operates in two streams: instance-level and bag-level. The instance-level stream evaluates critical instances determined by the instance classifier, which is used to calculate the attention weights for each instance. The bag-level stream computes the bag embeddings using the attention-weighted instance embeddings. The bag embeddings are processed by a convolutional layer and passed through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - calculate_attention: Calculate the attention weights for each instance - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Dual-stream MIL model. The model operates in two streams: instance-level and bag-level.\n The instance-level stream evaluates critical instances determined by the instance classifier, which is used\n to calculate the attention weights for each instance. The bag-level stream computes the bag embeddings\n using the attention-weighted instance embeddings. The bag embeddings are processed by a convolutional layer\n and passed through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - calculate_attention: Calculate the attention weights for each instance\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function dsmil.__init__>, '_initialize_weights': <function dsmil._initialize_weights>, 'forward': <function dsmil.forward>, 'calculate_attention': <function dsmil.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, return_attention=False)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.gated_attention_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleGated Attention MIL model. The model computes attention weights for each instance and aggregates the instance embeddings using the attention weights in a gated manner. The model then passes the aggregated embeddings through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - calculate_attention: Calculate the attention weights for each instance - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Gated Attention MIL model. The model computes attention weights for each instance and aggregates the instance\n embeddings using the attention weights in a gated manner. The model then passes the aggregated embeddings through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - calculate_attention: Calculate the attention weights for each instance\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function gated_attention_mil.__init__>, '_initialize_weights': <function gated_attention_mil._initialize_weights>, 'forward': <function gated_attention_mil.forward>, 'calculate_attention': <function gated_attention_mil.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- pathbench.models.aggregators.get_activation_function(activation_name: str)[source]
Return the corresponding activation function from a string name.
Args: - activation_name: Name of the activation function
Returns: - activation_function: Activation function
- class pathbench.models.aggregators.il_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleInstance-level MIL model. The model classifies each instance and aggregates the instance predictions using the mean operation. Useful for cases where a small number of relevant instances are present in each bag.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - bag_scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Instance-level MIL model. The model classifies each instance and aggregates the instance predictions\n using the mean operation. Useful for cases where a small number of relevant instances are present in each bag.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - bag_scores: Predicted class scores for in the bag\n ', '__init__': <function il_mil.__init__>, '_initialize_weights': <function il_mil._initialize_weights>, 'forward': <function il_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- pathbench.models.aggregators.initialize_weights(module)[source]
Initialize the weights of the model using Xavier initialization for linear layers and constant initialization for batch normalization layers.
Args: - module: The model to initialize
Returns: - None
- class pathbench.models.aggregators.linear_evaluation_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function=None, encoder_layers=1)[source]
Bases:
ModuleLinear Evaluation MIL model. The model passes the instance embeddings through a linear layer and then through a classifier, while not using any pooling operation or activation function. Therefore useful for linear evaluation of the instance embeddings.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Linear Evaluation MIL model. The model passes the instance embeddings through a linear layer and then\n through a classifier, while not using any pooling operation or activation function. Therefore useful\n for linear evaluation of the instance embeddings.\n \n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function linear_evaluation_mil.__init__>, '_initialize_weights': <function linear_evaluation_mil._initialize_weights>, 'forward': <function linear_evaluation_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function=None, encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.lse_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, r: float = 1.0, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleLog-sum-exp MIL model. The model computes the log-sum-exp pooling of the instance embeddings and passes the result through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - r: Scaling factor for the log-sum-exp pooling - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Log-sum-exp MIL model. The model computes the log-sum-exp pooling of the instance embeddings and passes the result\n through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - r: Scaling factor for the log-sum-exp pooling\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function lse_mil.__init__>, '_initialize_weights': <function lse_mil._initialize_weights>, 'forward': <function lse_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, r: float = 1.0, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.lstm_mil(n_feats: int, n_out: int, z_dim: int = 256, lstm_dim: int = 128, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleLSTM MIL model. The model uses an LSTM to process the instance embeddings and passes the final hidden state through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - lstm_dim: Dimension of the LSTM hidden state - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n LSTM MIL model. The model uses an LSTM to process the instance embeddings and passes the final hidden state\n through a classifier. \n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - lstm_dim: Dimension of the LSTM hidden state\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', 'use_lens': True, '__init__': <function lstm_mil.__init__>, '_initialize_weights': <function lstm_mil._initialize_weights>, 'forward': <function lstm_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, lstm_dim: int = 128, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, lens)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- use_lens = True
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.max_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleMax-pooling MIL model. The model computes the max pooling of the instance embeddings and passes the result through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Max-pooling MIL model. The model computes the max pooling of the instance embeddings and passes the result\n through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function max_mil.__init__>, '_initialize_weights': <function max_mil._initialize_weights>, 'forward': <function max_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.mean_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleMean-pooling MIL model. The model computes the mean pooling of the instance embeddings and passes the result through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Mean-pooling MIL model. The model computes the mean pooling of the instance embeddings and passes the result\n through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function mean_mil.__init__>, '_initialize_weights': <function mean_mil._initialize_weights>, 'forward': <function mean_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.perceiver_mil(n_feats: int, n_out: int, z_dim: int = 256, latent_dim: int = 128, num_latents: int = 16, num_layers: int = 6, num_heads: int = 8, dropout_p: float = 0.1, activation_function: str = 'ReLU', encoder_layers: int = 1)[source]
Bases:
ModulePerceiver MIL model. The model uses a learnable latent array to compute attention weights between the input features and the latent array. The model then applies transformer layers to the latent array and uses the CLS token for classification.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - latent_dim: Dimension of the latent array - num_latents: Number of learnable latents - num_layers: Number of transformer layers - num_heads: Number of attention heads - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - output: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Perceiver MIL model. The model uses a learnable latent array to compute attention weights between the input features\n and the latent array. The model then applies transformer layers to the latent array and uses the CLS token for classification.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - latent_dim: Dimension of the latent array\n - num_latents: Number of learnable latents\n - num_layers: Number of transformer layers\n - num_heads: Number of attention heads\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - output: Predicted class scores for in the bag\n ', '__init__': <function perceiver_mil.__init__>, '_initialize_weights': <function perceiver_mil._initialize_weights>, 'forward': <function perceiver_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, latent_dim: int = 128, num_latents: int = 16, num_layers: int = 6, num_heads: int = 8, dropout_p: float = 0.1, activation_function: str = 'ReLU', encoder_layers: int = 1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, attn_mask=None)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.topk_mil(n_feats: int, n_out: int, z_dim: int = 256, k: int = 20, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleTop-k MIL model. The model computes attention weights for each instance and selects the top-k instances based on these weights. The model then computes the weighted sum of the top-k instances and passes the result through a classifier. Useful for problems where the number of relevant instances can be estimated.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space
Methods: - forward: Forward pass through the model - calculate_attention: Calculate the attention weights for each instance - initialize_weights: Initialize the weights of the model
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Top-k MIL model. The model computes attention weights for each instance and selects the top-k instances\n based on these weights. The model then computes the weighted sum of the top-k instances and passes the result\n through a classifier. Useful for problems where the number of relevant instances can be estimated.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n\n Methods:\n - forward: Forward pass through the model\n - calculate_attention: Calculate the attention weights for each instance\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function topk_mil.__init__>, '_initialize_weights': <function topk_mil._initialize_weights>, 'forward': <function topk_mil.forward>, 'calculate_attention': <function topk_mil.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, k: int = 20, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, return_attention=False)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.varmil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleVariance MIL model. The model computes the variance and mean of the attention-weighted instance embeddings. The model then concatenates this mean and variance and passes the result through a classifier.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model - calculate_attention: Calculate the attention weights for each instance
Returns: - scores: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Variance MIL model. The model computes the variance and mean of the attention-weighted instance embeddings. \n The model then concatenates this mean and variance and passes the result through a classifier.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n - calculate_attention: Calculate the attention weights for each instance\n\n Returns:\n - scores: Predicted class scores for in the bag\n ', '__init__': <function varmil.__init__>, '_initialize_weights': <function varmil._initialize_weights>, 'forward': <function varmil.forward>, 'calculate_attention': <function varmil.calculate_attention>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1) None[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags, return_attention=False)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.aggregators.weighted_mean_mil(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Bases:
ModuleWeighted mean MIL model. The variance of the instance embeddings is used to compute instance weights. The instance embeddings are then aggregated using the computed weights. Useful for noisy data.
Args: - n_feats: Number of input features - n_out: Number of output classes - z_dim: Dimension of the latent space - dropout_p: Dropout probability - activation_function: Activation function to use in the encoder - encoder_layers: Number of layers in the encoder
Methods: - forward: Forward pass through the model - initialize_weights: Initialize the weights of the model
Returns: - output: Predicted class scores for in the bag
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.aggregators', '__doc__': '\n Weighted mean MIL model. The variance of the instance embeddings is used to compute instance weights.\n The instance embeddings are then aggregated using the computed weights. Useful for noisy data.\n\n Args:\n - n_feats: Number of input features\n - n_out: Number of output classes\n - z_dim: Dimension of the latent space\n - dropout_p: Dropout probability\n - activation_function: Activation function to use in the encoder\n - encoder_layers: Number of layers in the encoder\n\n Methods:\n - forward: Forward pass through the model\n - initialize_weights: Initialize the weights of the model\n\n Returns:\n - output: Predicted class scores for in the bag\n ', '__init__': <function weighted_mean_mil.__init__>, '_initialize_weights': <function weighted_mean_mil._initialize_weights>, 'forward': <function weighted_mean_mil.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(n_feats: int, n_out: int, z_dim: int = 256, dropout_p: float = 0.1, activation_function='ReLU', encoder_layers=1)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.aggregators'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(bags)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.feature_extractors.ResNetTrunk(*args, **kwargs)[source]
Bases:
ResNetResNet trunk without the final fully connected layer
- Parameters:
*args (list) – Variable length argument list
**kwargs (dict) – Keyword arguments
- fc
Fully connected
- Type:
nn.Linear
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n ResNet trunk without the final fully connected layer\n\n Parameters\n ----------\n *args : list\n Variable length argument list\n **kwargs : dict\n Keyword arguments\n\n Attributes\n ----------\n fc : nn.Linear\n Fully connected\n \n Methods\n -------\n forward(x)\n Forward pass of the model\n ', '__init__': <function ResNetTrunk.__init__>, 'forward': <function ResNetTrunk.forward>, '__annotations__': {'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(*args, **kwargs)[source]
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- __module__ = 'pathbench.models.feature_extractors'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_impl(x: Tensor) Tensor
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _make_layer(block: Type[BasicBlock | Bottleneck], planes: int, blocks: int, stride: int = 1, dilate: bool = False) Sequential
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(x)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.feature_extractors.VisionTransformerMoCoWithoutHead(pretext_token=True, stop_grad_conv1=False, **kwargs)[source]
Bases:
VisionTransformerVision Transformer model with MoCo pretraining, without the final fully connected layer
- Parameters:
*args (list) – Variable length argument list
**kwargs (dict) – Keyword arguments
pretext_token (bool) – Whether to add a pretext token
stop_grad_conv1 (bool) – Whether to stop gradient for the first convolutional layer
- num_prefix_tokens
The number of prefix tokens
- Type:
int
- pretext_token
The pretext token
- Type:
nn.Parameter
- embed_len
The length of the embedding
- Type:
int
- pos_embed
The positional embedding
- Type:
nn.Parameter
- embed_dim
The embedding dimension
- Type:
int
- patch_embed
The patch embedding layer
- Type:
PatchEmbed
- pos_drop
The positional dropout layer
- Type:
nn.Dropout
- blocks
The transformer blocks
- Type:
nn.Sequential
- norm
The layer normalization layer
- Type:
nn.LayerNorm
- cls_token
The class token
- Type:
nn.Parameter
- dist_token
The distance token
- Type:
nn.Parameter
- norm_pre
The layer normalization layer for the prefix tokens
- Type:
nn.LayerNorm
- T_destination = ~T_destination
- __annotations__ = {'__call__': 'Callable[..., Any]', '_backward_hooks': 'Dict[int, Callable]', '_backward_pre_hooks': 'Dict[int, Callable]', '_buffers': 'Dict[str, Optional[Tensor]]', '_compiled_call_impl': 'Optional[Callable]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_is_full_backward_hook': 'Optional[bool]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", '_non_persistent_buffers_set': 'Set[str]', '_parameters': 'Dict[str, Optional[Parameter]]', '_state_dict_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_version': 'int', 'call_super_init': 'bool', 'dump_patches': 'bool', 'dynamic_img_size': 'Final[bool]', 'forward': 'Callable[..., Any]', 'training': 'bool'}
- __call__(*args, **kwargs)
Call self as a function.
- __delattr__(name)
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Vision Transformer model with MoCo pretraining, without the final fully connected layer\n\n Parameters\n ----------\n *args : list\n Variable length argument list\n **kwargs : dict\n Keyword arguments\n pretext_token : bool\n Whether to add a pretext token\n stop_grad_conv1 : bool\n Whether to stop gradient for the first convolutional layer\n \n Attributes\n ----------\n num_prefix_tokens : int\n The number of prefix tokens\n pretext_token : nn.Parameter\n The pretext token\n embed_len : int\n The length of the embedding\n pos_embed : nn.Parameter\n The positional embedding\n embed_dim : int\n The embedding dimension\n patch_embed : PatchEmbed\n The patch embedding layer\n pos_drop : nn.Dropout\n The positional dropout layer\n blocks : nn.Sequential\n The transformer blocks\n norm : nn.LayerNorm\n The layer normalization layer\n cls_token : nn.Parameter\n The class token\n dist_token : nn.Parameter\n The distance token\n norm_pre : nn.LayerNorm\n The layer normalization layer for the prefix tokens\n \n Methods\n -------\n _pos_embed(x)\n Add positional embedding to the input tensor\n _ref_embed(ref)\n Add positional embedding to the reference tensor\n _pos_embed_with_ref(x, ref)\n Add positional embedding to the input tensor with reference\n forward_features(x, ref)\n Forward pass of the model for features\n forward(x, ref)\n Forward pass of the model\n build_2d_sincos_position_embedding()\n Build 2D sin-cos position embedding\n ', '__init__': <function VisionTransformerMoCoWithoutHead.__init__>, 'no_weight_decay': <function VisionTransformerMoCoWithoutHead.no_weight_decay>, '_pos_embed': <function VisionTransformerMoCoWithoutHead._pos_embed>, '_ref_embed': <function VisionTransformerMoCoWithoutHead._ref_embed>, '_pos_embed_with_ref': <function VisionTransformerMoCoWithoutHead._pos_embed_with_ref>, 'forward_features': <function VisionTransformerMoCoWithoutHead.forward_features>, 'forward': <function VisionTransformerMoCoWithoutHead.forward>, 'build_2d_sincos_position_embedding': <function VisionTransformerMoCoWithoutHead.build_2d_sincos_position_embedding>, '__annotations__': {'dynamic_img_size': 'Final[bool]', 'dump_patches': 'bool', '_version': 'int', 'training': 'bool', '_parameters': 'Dict[str, Optional[Parameter]]', '_buffers': 'Dict[str, Optional[Tensor]]', '_non_persistent_buffers_set': 'Set[str]', '_backward_pre_hooks': 'Dict[int, Callable]', '_backward_hooks': 'Dict[int, Callable]', '_is_full_backward_hook': 'Optional[bool]', '_forward_hooks': 'Dict[int, Callable]', '_forward_hooks_with_kwargs': 'Dict[int, bool]', '_forward_hooks_always_called': 'Dict[int, bool]', '_forward_pre_hooks': 'Dict[int, Callable]', '_forward_pre_hooks_with_kwargs': 'Dict[int, bool]', '_state_dict_hooks': 'Dict[int, Callable]', '_load_state_dict_pre_hooks': 'Dict[int, Callable]', '_state_dict_pre_hooks': 'Dict[int, Callable]', '_load_state_dict_post_hooks': 'Dict[int, Callable]', '_modules': "Dict[str, Optional['Module']]", 'call_super_init': 'bool', '_compiled_call_impl': 'Optional[Callable]', 'forward': 'Callable[..., Any]', '__call__': 'Callable[..., Any]'}})
- __dir__()
Default dir() implementation.
- __getattr__(name: str) Any
- __getstate__()
- __init__(pretext_token=True, stop_grad_conv1=False, **kwargs)[source]
- Parameters:
img_size – Input image size.
patch_size – Patch size.
in_chans – Number of image input channels.
num_classes – Mumber of classes for classification head.
global_pool – Type of global pooling for final sequence (default: ‘token’).
embed_dim – Transformer embedding dimension.
depth – Depth of transformer.
num_heads – Number of attention heads.
mlp_ratio – Ratio of mlp hidden dim to embedding dim.
qkv_bias – Enable bias for qkv projections if True.
init_values – Layer-scale init values (layer-scale enabled if not None).
class_token – Use class token.
no_embed_class – Don’t include position embeddings for class (or reg) tokens.
reg_tokens – Number of register tokens.
fc_norm – Pre head norm after pool (instead of before), if None, enabled when global_pool == ‘avg’.
drop_rate – Head dropout rate.
pos_drop_rate – Position embedding dropout rate.
attn_drop_rate – Attention dropout rate.
drop_path_rate – Stochastic depth rate.
weight_init – Weight initialization scheme.
fix_init – Apply weight initialization fix (scaling w/ layer index).
embed_layer – Patch embedding layer.
norm_layer – Normalization layer.
act_layer – MLP activation layer.
block_fn – Transformer block layer.
- __module__ = 'pathbench.models.feature_extractors'
- __repr__()
Return repr(self).
- __setattr__(name: str, value: Tensor | Module) None
Implement setattr(self, name, value).
- __setstate__(state)
- __weakref__
list of weak references to the object (if defined)
- _apply(fn, recurse=True)
- _backward_hooks: Dict[int, Callable]
- _backward_pre_hooks: Dict[int, Callable]
- _buffers: Dict[str, Tensor | None]
- _call_impl(*args, **kwargs)
- _compiled_call_impl: Callable | None = None
- _forward_hooks: Dict[int, Callable]
- _forward_hooks_always_called: Dict[int, bool]
- _forward_hooks_with_kwargs: Dict[int, bool]
- _forward_pre_hooks: Dict[int, Callable]
- _forward_pre_hooks_with_kwargs: Dict[int, bool]
- _get_backward_hooks()
Return the backward hooks for use in the call function.
It returns two lists, one with the full backward hooks and one with the non-full backward hooks.
- _get_backward_pre_hooks()
- _get_name()
- _init_weights(m: Module) None
- _is_full_backward_hook: bool | None
- _load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
Copy parameters and buffers from
state_dictinto only this module, but not its descendants.This is called on every submodule in
load_state_dict(). Metadata saved for this module in inputstate_dictis provided aslocal_metadata. For state dicts without metadata,local_metadatais empty. Subclasses can achieve class-specific backward compatible loading using the version number at local_metadata.get(“version”, None). Additionally,local_metadatacan also contain the key assign_to_params_buffers that indicates whether keys should be assigned their corresponding tensor in the state_dict.Note
state_dictis not the same object as the inputstate_dicttoload_state_dict(). So it can be modified.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
prefix (str) – the prefix for parameters and buffers used in this module
local_metadata (dict) – a dict containing the metadata for this module. See
strict (bool) – whether to strictly enforce that the keys in
state_dictwithprefixmatch the names of parameters and buffers in this modulemissing_keys (list of str) – if
strict=True, add missing keys to this listunexpected_keys (list of str) – if
strict=True, add unexpected keys to this listerror_msgs (list of str) – error messages should be added to this list, and will be reported together in
load_state_dict()
- _load_state_dict_post_hooks: Dict[int, Callable]
- _load_state_dict_pre_hooks: Dict[int, Callable]
- _maybe_warn_non_full_backward_hook(inputs, result, grad_fn)
- _modules: Dict[str, 'Module' | None]
- _named_members(get_members_fn, prefix='', recurse=True, remove_duplicate: bool = True)
Help yield various names + members of modules.
- _non_persistent_buffers_set: Set[str]
- _parameters: Dict[str, Parameter | None]
- _register_load_state_dict_pre_hook(hook, with_module=False)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments: state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs, before loading state_dict into self. These arguments are exactly the same as those of _load_from_state_dict.
If
with_moduleisTrue, then the first argument to the hook is an instance of the module.- Parameters:
hook (Callable) – Callable hook that will be invoked before loading the state dict.
with_module (bool, optional) – Whether or not to pass the module instance to the hook as the first parameter.
- _register_state_dict_hook(hook)
Register a state-dict hook.
These hooks will be called with arguments: self, state_dict, prefix, local_metadata, after the state_dict of self is set. Note that only parameters and buffers of self or its children are guaranteed to exist in state_dict. The hooks may modify state_dict inplace or return a new one.
- _replicate_for_data_parallel()
- _save_to_state_dict(destination, prefix, keep_vars)
Save module state to the destination dictionary.
The destination dictionary will contain the state of the module, but not its descendants. This is called on every submodule in
state_dict().In rare cases, subclasses can achieve class-specific behavior by overriding this method with custom logic.
- Parameters:
destination (dict) – a dict where state will be stored
prefix (str) – the prefix for parameters and buffers used in this module
- _slow_forward(*input, **kwargs)
- _state_dict_hooks: Dict[int, Callable]
- _state_dict_pre_hooks: Dict[int, Callable]
- _version: int = 1
This allows better BC support for
load_state_dict(). Instate_dict(), the version number will be saved as in the attribute _metadata of the returned state dict, and thus pickled. _metadata is a dictionary with keys that follow the naming convention of state dict. See_load_from_state_dicton how to use this information in loading.If new parameters/buffers are added/removed from a module, this number shall be bumped, and the module’s _load_from_state_dict method can compare the version number and do appropriate changes if the state dict is from before the change.
- _wrapped_call_impl(*args, **kwargs)
- add_module(name: str, module: Module | None) None
Add a child module to the current module.
The module can be accessed as an attribute using the given name.
- Parameters:
name (str) – name of the child module. The child module can be accessed from this module using the given name
module (Module) – child module to be added to the module.
- apply(fn: Callable[[Module], None]) T
Apply
fnrecursively to every submodule (as returned by.children()) as well as self.Typical use includes initializing the parameters of a model (see also nn-init-doc).
- Parameters:
fn (
Module-> None) – function to be applied to each submodule- Returns:
self
- Return type:
Module
Example:
>>> @torch.no_grad() >>> def init_weights(m): >>> print(m) >>> if type(m) == nn.Linear: >>> m.weight.fill_(1.0) >>> print(m.weight) >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) >>> net.apply(init_weights) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Linear(in_features=2, out_features=2, bias=True) Parameter containing: tensor([[1., 1.], [1., 1.]], requires_grad=True) Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )
- bfloat16() T
Casts all floating point parameters and buffers to
bfloat16datatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- buffers(recurse: bool = True) Iterator[Tensor]
Return an iterator over module buffers.
- Parameters:
recurse (bool) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module.
- Yields:
torch.Tensor – module buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for buf in model.buffers(): >>> print(type(buf), buf.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- call_super_init: bool = False
- children() Iterator[Module]
Return an iterator over immediate children modules.
- Yields:
Module – a child module
- compile(*args, **kwargs)
Compile this Module’s forward using
torch.compile().This Module’s __call__ method is compiled and all arguments are passed as-is to
torch.compile().See
torch.compile()for details on the arguments for this function.
- cpu() T
Move all model parameters and buffers to the CPU.
Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- cuda(device: int | device | None = None) T
Move all model parameters and buffers to the GPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on GPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- double() T
Casts all floating point parameters and buffers to
doubledatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- dump_patches: bool = False
- dynamic_img_size: Final[bool]
- eval() T
Set the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.This is equivalent with
self.train(False).See locally-disable-grad-doc for a comparison between .eval() and several similar mechanisms that may be confused with it.
- Returns:
self
- Return type:
Module
- extra_repr() str
Set the extra representation of the module.
To print customized extra information, you should re-implement this method in your own modules. Both single-line and multi-line strings are acceptable.
- fix_init_weight()
- float() T
Casts all floating point parameters and buffers to
floatdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- forward(x, ref=None)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- forward_head(x: Tensor, pre_logits: bool = False) Tensor
- forward_intermediates(x: Tensor, indices: int | List[int] | Tuple[int] | None = None, return_prefix_tokens: bool = False, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False) List[Tensor] | Tuple[Tensor, List[Tensor]]
Forward features that returns intermediates.
- Parameters:
x – Input image tensor
indices – Take last n blocks if int, all if None, select matching indices if sequence
return_prefix_tokens – Return both prefix and spatial intermediate tokens
norm – Apply norm layer to all intermediates
stop_early – Stop iterating over blocks when last desired intermediate hit
output_fmt – Shape of intermediate feature outputs
intermediates_only – Only return intermediate features
Returns:
- get_buffer(target: str) Tensor
Return the buffer given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the buffer to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The buffer referenced by
target- Return type:
torch.Tensor
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not a buffer
- get_classifier() Module
- get_extra_state() Any
Return any extra state to include in the module’s state_dict.
Implement this and a corresponding
set_extra_state()for your module if you need to store extra state. This function is called when building the module’s state_dict().Note that extra state should be picklable to ensure working serialization of the state_dict. We only provide provide backwards compatibility guarantees for serializing Tensors; other objects may break backwards compatibility if their serialized pickled form changes.
- Returns:
Any extra state to store in the module’s state_dict
- Return type:
object
- get_intermediate_layers(x: Tensor, n: int | List[int] | Tuple[int] = 1, reshape: bool = False, return_prefix_tokens: bool = False, norm: bool = False) List[Tensor]
Intermediate layer accessor inspired by DINO / DINOv2 interface. NOTE: This API is for backwards compat, favour using forward_intermediates() directly.
- get_parameter(target: str) Parameter
Return the parameter given by
targetif it exists, otherwise throw an error.See the docstring for
get_submodulefor a more detailed explanation of this method’s functionality as well as how to correctly specifytarget.- Parameters:
target – The fully-qualified string name of the Parameter to look for. (See
get_submodulefor how to specify a fully-qualified string.)- Returns:
The Parameter referenced by
target- Return type:
torch.nn.Parameter
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Parameter
- get_submodule(target: str) Module
Return the submodule given by
targetif it exists, otherwise throw an error.For example, let’s say you have an
nn.ModuleAthat looks like this:A( (net_b): Module( (net_c): Module( (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2)) ) (linear): Linear(in_features=100, out_features=200, bias=True) ) )(The diagram shows an
nn.ModuleA.Ahas a nested submodulenet_b, which itself has two submodulesnet_candlinear.net_cthen has a submoduleconv.)To check whether or not we have the
linearsubmodule, we would callget_submodule("net_b.linear"). To check whether we have theconvsubmodule, we would callget_submodule("net_b.net_c.conv").The runtime of
get_submoduleis bounded by the degree of module nesting intarget. A query againstnamed_modulesachieves the same result, but it is O(N) in the number of transitive modules. So, for a simple check to see if some submodule exists,get_submoduleshould always be used.- Parameters:
target – The fully-qualified string name of the submodule to look for. (See above example for how to specify a fully-qualified string.)
- Returns:
The submodule referenced by
target- Return type:
torch.nn.Module
- Raises:
AttributeError – If the target string references an invalid path or resolves to something that is not an
nn.Module
- group_matcher(coarse: bool = False) Dict
- half() T
Casts all floating point parameters and buffers to
halfdatatype.Note
This method modifies the module in-place.
- Returns:
self
- Return type:
Module
- init_weights(mode: str = '') None
- ipu(device: int | device | None = None) T
Move all model parameters and buffers to the IPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on IPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- load_pretrained(checkpoint_path: str, prefix: str = '') None
- load_state_dict(state_dict: Mapping[str, Any], strict: bool = True, assign: bool = False)
Copy parameters and buffers from
state_dictinto this module and its descendants.If
strictisTrue, then the keys ofstate_dictmust exactly match the keys returned by this module’sstate_dict()function.Warning
If
assignisTruethe optimizer must be created after the call toload_state_dict.- Parameters:
state_dict (dict) – a dict containing parameters and persistent buffers.
strict (bool, optional) – whether to strictly enforce that the keys in
state_dictmatch the keys returned by this module’sstate_dict()function. Default:Trueassign (bool, optional) – whether to assign items in the state dictionary to their corresponding keys in the module instead of copying them inplace into the module’s current parameters and buffers. When
False, the properties of the tensors in the current module are preserved while whenTrue, the properties of the Tensors in the state dict are preserved. Default:False
- Returns:
missing_keys is a list of str containing the missing keys
unexpected_keys is a list of str containing the unexpected keys
- Return type:
NamedTuplewithmissing_keysandunexpected_keysfields
Note
If a parameter or buffer is registered as
Noneand its corresponding key exists instate_dict,load_state_dict()will raise aRuntimeError.
- modules() Iterator[Module]
Return an iterator over all modules in the network.
- Yields:
Module – a module in the network
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.modules()): ... print(idx, '->', m) 0 -> Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) ) 1 -> Linear(in_features=2, out_features=2, bias=True)
- named_buffers(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Tensor]]
Return an iterator over module buffers, yielding both the name of the buffer as well as the buffer itself.
- Parameters:
prefix (str) – prefix to prepend to all buffer names.
recurse (bool, optional) – if True, then yields buffers of this module and all submodules. Otherwise, yields only buffers that are direct members of this module. Defaults to True.
remove_duplicate (bool, optional) – whether to remove the duplicated buffers in the result. Defaults to True.
- Yields:
(str, torch.Tensor) – Tuple containing the name and buffer
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, buf in self.named_buffers(): >>> if name in ['running_var']: >>> print(buf.size())
- named_children() Iterator[Tuple[str, Module]]
Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.
- Yields:
(str, Module) – Tuple containing a name and child module
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, module in model.named_children(): >>> if name in ['conv4', 'conv5']: >>> print(module)
- named_modules(memo: Set[Module] | None = None, prefix: str = '', remove_duplicate: bool = True)
Return an iterator over all modules in the network, yielding both the name of the module as well as the module itself.
- Parameters:
memo – a memo to store the set of modules already added to the result
prefix – a prefix that will be added to the name of the module
remove_duplicate – whether to remove the duplicated module instances in the result or not
- Yields:
(str, Module) – Tuple of name and module
Note
Duplicate modules are returned only once. In the following example,
lwill be returned only once.Example:
>>> l = nn.Linear(2, 2) >>> net = nn.Sequential(l, l) >>> for idx, m in enumerate(net.named_modules()): ... print(idx, '->', m) 0 -> ('', Sequential( (0): Linear(in_features=2, out_features=2, bias=True) (1): Linear(in_features=2, out_features=2, bias=True) )) 1 -> ('0', Linear(in_features=2, out_features=2, bias=True))
- named_parameters(prefix: str = '', recurse: bool = True, remove_duplicate: bool = True) Iterator[Tuple[str, Parameter]]
Return an iterator over module parameters, yielding both the name of the parameter as well as the parameter itself.
- Parameters:
prefix (str) – prefix to prepend to all parameter names.
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
remove_duplicate (bool, optional) – whether to remove the duplicated parameters in the result. Defaults to True.
- Yields:
(str, Parameter) – Tuple containing the name and parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for name, param in self.named_parameters(): >>> if name in ['bias']: >>> print(param.size())
- parameters(recurse: bool = True) Iterator[Parameter]
Return an iterator over module parameters.
This is typically passed to an optimizer.
- Parameters:
recurse (bool) – if True, then yields parameters of this module and all submodules. Otherwise, yields only parameters that are direct members of this module.
- Yields:
Parameter – module parameter
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> for param in model.parameters(): >>> print(type(param), param.size()) <class 'torch.Tensor'> (20L,) <class 'torch.Tensor'> (20L, 1L, 5L, 5L)
- pool(x: Tensor, pool_type: str | None = None) Tensor
- prune_intermediate_layers(indices: int | List[int] | Tuple[int] = 1, prune_norm: bool = False, prune_head: bool = True)
Prune layers not required for specified intermediates.
- register_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor]) RemovableHandle
Register a backward hook on the module.
This function is deprecated in favor of
register_full_backward_hook()and the behavior of this function will change in future versions.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_buffer(name: str, tensor: Tensor | None, persistent: bool = True) None
Add a buffer to the module.
This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s
running_meanis not a parameter, but is part of the module’s state. Buffers, by default, are persistent and will be saved alongside parameters. This behavior can be changed by settingpersistenttoFalse. The only difference between a persistent buffer and a non-persistent buffer is that the latter will not be a part of this module’sstate_dict.Buffers can be accessed as attributes using given names.
- Parameters:
name (str) – name of the buffer. The buffer can be accessed from this module using the given name
tensor (Tensor or None) – buffer to be registered. If
None, then operations that run on buffers, such ascuda, are ignored. IfNone, the buffer is not included in the module’sstate_dict.persistent (bool) – whether the buffer is part of this module’s
state_dict.
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> self.register_buffer('running_mean', torch.zeros(num_features))
- register_forward_hook(hook: Callable[[T, Tuple[Any, ...], Any], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any], Any], Any | None], *, prepend: bool = False, with_kwargs: bool = False, always_call: bool = False) RemovableHandle
Register a forward hook on the module.
The hook will be called every time after
forward()has computed an output.If
with_kwargsisFalseor not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the output. It can modify the input inplace but it will not have effect on forward since this is called afterforward()is called. The hook should have the following signature:hook(module, args, output) -> None or modified output
If
with_kwargsisTrue, the forward hook will be passed thekwargsgiven to the forward function and be expected to return the output possibly modified. The hook should have the following signature:hook(module, args, kwargs, output) -> None or modified output
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If
True, the providedhookwill be fired before all existingforwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforwardhooks on thistorch.nn.modules.Module. Note that globalforwardhooks registered withregister_module_forward_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If
True, thehookwill be passed the kwargs given to the forward function. Default:Falsealways_call (bool) – If
Truethehookwill be run regardless of whether an exception is raised while calling the Module. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_forward_pre_hook(hook: Callable[[T, Tuple[Any, ...]], Any | None] | Callable[[T, Tuple[Any, ...], Dict[str, Any]], Tuple[Any, Dict[str, Any]] | None], *, prepend: bool = False, with_kwargs: bool = False) RemovableHandle
Register a forward pre-hook on the module.
The hook will be called every time before
forward()is invoked.If
with_kwargsis false or not specified, the input contains only the positional arguments given to the module. Keyword arguments won’t be passed to the hooks and only to theforward. The hook can modify the input. User can either return a tuple or a single modified value in the hook. We will wrap the value into a tuple if a single value is returned (unless that value is already a tuple). The hook should have the following signature:hook(module, args) -> None or modified input
If
with_kwargsis true, the forward pre-hook will be passed the kwargs given to the forward function. And if the hook modifies the input, both the args and kwargs should be returned. The hook should have the following signature:hook(module, args, kwargs) -> None or a tuple of modified input and kwargs
- Parameters:
hook (Callable) – The user defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingforward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingforward_prehooks on thistorch.nn.modules.Module. Note that globalforward_prehooks registered withregister_module_forward_pre_hook()will fire before all hooks registered by this method. Default:Falsewith_kwargs (bool) – If true, the
hookwill be passed the kwargs given to the forward function. Default:False
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward hook on the module.
The hook will be called every time the gradients with respect to a module are computed, i.e. the hook will execute if and only if the gradients with respect to module outputs are computed. The hook should have the following signature:
hook(module, grad_input, grad_output) -> tuple(Tensor) or None
The
grad_inputandgrad_outputare tuples that contain the gradients with respect to the inputs and outputs respectively. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the input that will be used in place ofgrad_inputin subsequent computations.grad_inputwill only correspond to the inputs given as positional arguments and all kwarg arguments are ignored. Entries ingrad_inputandgrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs or outputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackwardhooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackwardhooks on thistorch.nn.modules.Module. Note that globalbackwardhooks registered withregister_module_full_backward_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_full_backward_pre_hook(hook: Callable[[Module, Tuple[Tensor, ...] | Tensor], None | Tuple[Tensor, ...] | Tensor], prepend: bool = False) RemovableHandle
Register a backward pre-hook on the module.
The hook will be called every time the gradients for the module are computed. The hook should have the following signature:
hook(module, grad_output) -> tuple[Tensor] or None
The
grad_outputis a tuple. The hook should not modify its arguments, but it can optionally return a new gradient with respect to the output that will be used in place ofgrad_outputin subsequent computations. Entries ingrad_outputwill beNonefor all non-Tensor arguments.For technical reasons, when this hook is applied to a Module, its forward function will receive a view of each Tensor passed to the Module. Similarly the caller will receive a view of each Tensor returned by the Module’s forward function.
Warning
Modifying inputs inplace is not allowed when using backward hooks and will raise an error.
- Parameters:
hook (Callable) – The user-defined hook to be registered.
prepend (bool) – If true, the provided
hookwill be fired before all existingbackward_prehooks on thistorch.nn.modules.Module. Otherwise, the providedhookwill be fired after all existingbackward_prehooks on thistorch.nn.modules.Module. Note that globalbackward_prehooks registered withregister_module_full_backward_pre_hook()will fire before all hooks registered by this method.
- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_load_state_dict_post_hook(hook)
Register a post hook to be run after module’s
load_state_dictis called.- It should have the following signature::
hook(module, incompatible_keys) -> None
The
moduleargument is the current module that this hook is registered on, and theincompatible_keysargument is aNamedTupleconsisting of attributesmissing_keysandunexpected_keys.missing_keysis alistofstrcontaining the missing keys andunexpected_keysis alistofstrcontaining the unexpected keys.The given incompatible_keys can be modified inplace if needed.
Note that the checks performed when calling
load_state_dict()withstrict=Trueare affected by modifications the hook makes tomissing_keysorunexpected_keys, as expected. Additions to either set of keys will result in an error being thrown whenstrict=True, and clearing out both missing and unexpected keys will avoid an error.- Returns:
a handle that can be used to remove the added hook by calling
handle.remove()- Return type:
torch.utils.hooks.RemovableHandle
- register_module(name: str, module: Module | None) None
Alias for
add_module().
- register_parameter(name: str, param: Parameter | None) None
Add a parameter to the module.
The parameter can be accessed as an attribute using given name.
- Parameters:
name (str) – name of the parameter. The parameter can be accessed from this module using the given name
param (Parameter or None) – parameter to be added to the module. If
None, then operations that run on parameters, such ascuda, are ignored. IfNone, the parameter is not included in the module’sstate_dict.
- register_state_dict_pre_hook(hook)
Register a pre-hook for the
load_state_dict()method.These hooks will be called with arguments:
self,prefix, andkeep_varsbefore callingstate_dictonself. The registered hooks can be used to perform pre-processing before thestate_dictcall is made.
- requires_grad_(requires_grad: bool = True) T
Change if autograd should record operations on parameters in this module.
This method sets the parameters’
requires_gradattributes in-place.This method is helpful for freezing part of the module for finetuning or training parts of a model individually (e.g., GAN training).
See locally-disable-grad-doc for a comparison between .requires_grad_() and several similar mechanisms that may be confused with it.
- Parameters:
requires_grad (bool) – whether autograd should record operations on parameters in this module. Default:
True.- Returns:
self
- Return type:
Module
- reset_classifier(num_classes: int, global_pool: str | None = None)
- set_extra_state(state: Any)
Set extra state contained in the loaded state_dict.
This function is called from
load_state_dict()to handle any extra state found within the state_dict. Implement this function and a correspondingget_extra_state()for your module if you need to store extra state within its state_dict.- Parameters:
state (dict) – Extra state from the state_dict
- set_grad_checkpointing(enable: bool = True) None
See
torch.Tensor.share_memory_().
- state_dict(*args, destination=None, prefix='', keep_vars=False)
Return a dictionary containing references to the whole state of the module.
Both parameters and persistent buffers (e.g. running averages) are included. Keys are corresponding parameter and buffer names. Parameters and buffers set to
Noneare not included.Note
The returned object is a shallow copy. It contains references to the module’s parameters and buffers.
Warning
Currently
state_dict()also accepts positional arguments fordestination,prefixandkeep_varsin order. However, this is being deprecated and keyword arguments will be enforced in future releases.Warning
Please avoid the use of argument
destinationas it is not designed for end-users.- Parameters:
destination (dict, optional) – If provided, the state of module will be updated into the dict and the same object is returned. Otherwise, an
OrderedDictwill be created and returned. Default:None.prefix (str, optional) – a prefix added to parameter and buffer names to compose the keys in state_dict. Default:
''.keep_vars (bool, optional) – by default the
Tensors returned in the state dict are detached from autograd. If it’s set toTrue, detaching will not be performed. Default:False.
- Returns:
a dictionary containing a whole state of the module
- Return type:
dict
Example:
>>> # xdoctest: +SKIP("undefined vars") >>> module.state_dict().keys() ['bias', 'weight']
- to(*args, **kwargs)
Move and/or cast the parameters and buffers.
This can be called as
- to(device=None, dtype=None, non_blocking=False)
- to(dtype, non_blocking=False)
- to(tensor, non_blocking=False)
- to(memory_format=torch.channels_last)
Its signature is similar to
torch.Tensor.to(), but only accepts floating point or complexdtypes. In addition, this method will only cast the floating point or complex parameters and buffers todtype(if given). The integral parameters and buffers will be moveddevice, if that is given, but with dtypes unchanged. Whennon_blockingis set, it tries to convert/move asynchronously with respect to the host if possible, e.g., moving CPU Tensors with pinned memory to CUDA devices.See below for examples.
Note
This method modifies the module in-place.
- Parameters:
device (
torch.device) – the desired device of the parameters and buffers in this moduledtype (
torch.dtype) – the desired floating point or complex dtype of the parameters and buffers in this moduletensor (torch.Tensor) – Tensor whose dtype and device are the desired dtype and device for all parameters and buffers in this module
memory_format (
torch.memory_format) – the desired memory format for 4D parameters and buffers in this module (keyword only argument)
- Returns:
self
- Return type:
Module
Examples:
>>> # xdoctest: +IGNORE_WANT("non-deterministic") >>> linear = nn.Linear(2, 2) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]]) >>> linear.to(torch.double) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1913, -0.3420], [-0.5113, -0.2325]], dtype=torch.float64) >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1) >>> gpu1 = torch.device("cuda:1") >>> linear.to(gpu1, dtype=torch.half, non_blocking=True) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1') >>> cpu = torch.device("cpu") >>> linear.to(cpu) Linear(in_features=2, out_features=2, bias=True) >>> linear.weight Parameter containing: tensor([[ 0.1914, -0.3420], [-0.5112, -0.2324]], dtype=torch.float16) >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble) >>> linear.weight Parameter containing: tensor([[ 0.3741+0.j, 0.2382+0.j], [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128) >>> linear(torch.ones(3, 2, dtype=torch.cdouble)) tensor([[0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j], [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)
- to_empty(*, device: int | str | device | None, recurse: bool = True) T
Move the parameters and buffers to the specified device without copying storage.
- Parameters:
device (
torch.device) – The desired device of the parameters and buffers in this module.recurse (bool) – Whether parameters and buffers of submodules should be recursively moved to the specified device.
- Returns:
self
- Return type:
Module
- train(mode: bool = True) T
Set the module in training mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.- Parameters:
mode (bool) – whether to set training mode (
True) or evaluation mode (False). Default:True.- Returns:
self
- Return type:
Module
- training: bool
- type(dst_type: dtype | str) T
Casts all parameters and buffers to
dst_type.Note
This method modifies the module in-place.
- Parameters:
dst_type (type or string) – the desired type
- Returns:
self
- Return type:
Module
- xpu(device: int | device | None = None) T
Move all model parameters and buffers to the XPU.
This also makes associated parameters and buffers different objects. So it should be called before constructing optimizer if the module will live on XPU while being optimized.
Note
This method modifies the module in-place.
- Parameters:
device (int, optional) – if specified, all parameters will be copied to that device
- Returns:
self
- Return type:
Module
- zero_grad(set_to_none: bool = True) None
Reset gradients of all model parameters.
See similar function under
torch.optim.Optimizerfor more context.- Parameters:
set_to_none (bool) – instead of setting to zero, set the grads to None. See
torch.optim.Optimizer.zero_grad()for details.
- class pathbench.models.feature_extractors.barlow_twins(tile_px=256)[source]
Bases:
TorchFeatureExtractorLunit-IO Barlow Twins feature extractor, with ResNet-50 backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The ResNet-50 model
- Type:
ResNet50 truncated
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Lunit-IO Barlow Twins feature extractor, with ResNet-50 backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : ResNet50 truncated\n The ResNet-50 model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'barlow_twins', '__init__': <function barlow_twins.__init__>, 'dump_config': <function barlow_twins.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'barlow_twins'
- class pathbench.models.feature_extractors.beph(tile_px=256)[source]
Bases:
TorchFeatureExtractorBEPH feature extractor, with base Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n BEPH feature extractor, with base Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'beph', '__init__': <function beph.__init__>, 'dump_config': <function beph.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'beph'
- class pathbench.models.feature_extractors.conch(tile_px=256)[source]
Bases:
TorchFeatureExtractor- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', 'create_model_from_pretrained': <function create_model_from_pretrained>, '__init__': <function conch.__init__>, '__doc__': None, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- create_model_from_pretrained(checkpoint_path: str | None = None, device: str | device = 'cpu', jit: bool = False, force_image_size: int | Tuple[int, int] | None = None, return_transform: bool = True, image_mean: Tuple[float, ...] | None = None, image_std: Tuple[float, ...] | None = None, cache_dir: str | None = None, hf_auth_token: str | None = None)
- dump_config()
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'generic_extractor'
- class pathbench.models.feature_extractors.dino(tile_px=256)[source]
Bases:
TorchFeatureExtractorLunit-IO DINO feature extractor, with ViT-Small backbone https://openaccess.thecvf.com/content/CVPR2023/html/Kang_Benchmarking_Self-Supervised_Learning_on_Diverse_Pathology_Datasets_CVPR_2023_paper.html :param tile_px: The size of the tile :type tile_px: int
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Lunit-IO DINO feature extractor, with ViT-Small backbone\n https://openaccess.thecvf.com/content/CVPR2023/html/Kang_Benchmarking_Self-Supervised_Learning_on_Diverse_Pathology_Datasets_CVPR_2023_paper.html\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'dino', '__init__': <function dino.__init__>, 'dump_config': <function dino.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'dino'
- pathbench.models.feature_extractors.download_pretrained_weights(key: str, destination: str)[source]
Download the pretrained weights for the model
- Parameters:
key (str) – The key for the model
destination (str) – The path to save the pretrained weights
- class pathbench.models.feature_extractors.exaone_path(tile_px=256)[source]
Bases:
TorchFeatureExtractorEXAONE Path feature extractor, with Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n EXAONE Path feature extractor, with Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'exaone_path', '__init__': <function exaone_path.__init__>, 'dump_config': <function exaone_path.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'exaone_path'
- pathbench.models.feature_extractors.get_pretrained_url(key: str)[source]
Get the URL for the pretrained weights of the model
- Parameters:
key (str) – The key for the model
- Returns:
The URL for the pretrained weights of the model
- Return type:
str
- pathbench.models.feature_extractors.get_pretrained_url_vit(key: str)[source]
Get the URL for the pretrained weights of the Vision Transformer model
- Parameters:
key (str) – The key for the model
- Returns:
The URL for the pretrained weights of the model
- Return type:
str
- class pathbench.models.feature_extractors.gigapath(tile_px=256)[source]
Bases:
TorchFeatureExtractorProv-GigaPath feature extractor, with Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Prov-GigaPath feature extractor, with Vision Transformer backbone\n\n Parameters \n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'gigapath', '__init__': <function gigapath.__init__>, 'dump_config': <function gigapath.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'gigapath'
- class pathbench.models.feature_extractors.h_optimus_0(tile_px=256)[source]
Bases:
TorchFeatureExtractorH-Optimus feature extractor, with large Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n H-Optimus feature extractor, with large Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'h_optimus_0', '__init__': <function h_optimus_0.__init__>, 'dump_config': <function h_optimus_0.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'h_optimus_0'
- class pathbench.models.feature_extractors.hibou_b(tile_px=256)[source]
Bases:
TorchFeatureExtractorHibou B feature extractor, with base Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Hibou model
- Type:
HibouEmbedder
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Hibou B feature extractor, with base Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : HibouEmbedder\n The Hibou model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'hibou_b', '__init__': <function hibou_b.__init__>, 'dump_config': <function hibou_b.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'hibou_b'
- class pathbench.models.feature_extractors.hibou_l(tile_px=256)[source]
Bases:
TorchFeatureExtractorHibou L feature extractor, with large Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Hibou model
- Type:
HibouEmbedder
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Hibou L feature extractor, with large Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : HibouEmbedder\n The Hibou model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'hibou_l', '__init__': <function hibou_l.__init__>, 'dump_config': <function hibou_l.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'hibou_l'
- class pathbench.models.feature_extractors.kaiko_b16(tile_px=256)[source]
Bases:
TorchFeatureExtractorKaiko B16 feature extractor, with base Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Kaiko B16 feature extractor, with base Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n\n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'kaiko_b16', '__init__': <function kaiko_b16.__init__>, 'dump_config': <function kaiko_b16.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'kaiko_b16'
- class pathbench.models.feature_extractors.kaiko_b8(tile_px=256)[source]
Bases:
TorchFeatureExtractorKaiko B8 feature extractor, with base Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Kaiko B8 feature extractor, with base Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n\n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'kaiko_b8', '__init__': <function kaiko_b8.__init__>, 'dump_config': <function kaiko_b8.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'kaiko_b8'
- class pathbench.models.feature_extractors.kaiko_l14(tile_px=256)[source]
Bases:
TorchFeatureExtractorKaiko L14 feature extractor, with large Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Kaiko L14 feature extractor, with large Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n\n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'kaiko_l14', '__init__': <function kaiko_l14.__init__>, 'dump_config': <function kaiko_l14.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'kaiko_l14'
- class pathbench.models.feature_extractors.kaiko_s16(tile_px=256)[source]
Bases:
TorchFeatureExtractorKaiko S16 feature extractor, with small Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Kaiko S16 feature extractor, with small Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n\n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'kaiko_s16', '__init__': <function kaiko_s16.__init__>, 'dump_config': <function kaiko_s16.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'kaiko_s16'
- class pathbench.models.feature_extractors.kaiko_s8(tile_px=256)[source]
Bases:
TorchFeatureExtractorKaiko S8 feature extractor, with small Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Kaiko S8 feature extractor, with small Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n\n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'kaiko_s8', '__init__': <function kaiko_s8.__init__>, 'dump_config': <function kaiko_s8.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'kaiko_s8'
- class pathbench.models.feature_extractors.mocov2(tile_px=256)[source]
Bases:
TorchFeatureExtractorLunit-IO MoCoV2 feature extractor, with ResNet-50 backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The ResNet-50 model
- Type:
ResNet50 truncated
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Lunit-IO MoCoV2 feature extractor, with ResNet-50 backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : ResNet50 truncated\n The ResNet-50 model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'mocov2', '__init__': <function mocov2.__init__>, 'dump_config': <function mocov2.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'mocov2'
- class pathbench.models.feature_extractors.pathoduet_he(tile_px=256)[source]
Bases:
TorchFeatureExtractorPathoDuet HE-trained feature extractor, with Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n PathoDuet HE-trained feature extractor, with Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformerMoCoWithoutHead \n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict \n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'pathoduet_he', '__init__': <function pathoduet_he.__init__>, 'dump_config': <function pathoduet_he.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'pathoduet_he'
- class pathbench.models.feature_extractors.pathoduet_ihc(tile_px=256)[source]
Bases:
TorchFeatureExtractorPathoDuet IHC-trained feature extractor, with Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n PathoDuet IHC-trained feature extractor, with Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformerMoCoWithoutHead \n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict \n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'pathoduet_ihc', '__init__': <function pathoduet_ihc.__init__>, 'dump_config': <function pathoduet_ihc.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'pathoduet_ihc'
- class pathbench.models.feature_extractors.phikon(tile_px=256)[source]
Bases:
TorchFeatureExtractorPhikon feature extractor, with ViT-Large backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Phikon feature extractor, with ViT-Large backbone\n\n Parameters \n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'phikon', '__init__': <function phikon.__init__>, 'dump_config': <function phikon.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'phikon'
- class pathbench.models.feature_extractors.phikon_v2(tile_px=256)[source]
Bases:
TorchFeatureExtractorV2 of the Phikon feature extractor, with Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n V2 of the Phikon feature extractor, with Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'phikon_v2', '__init__': <function phikon_v2.__init__>, 'dump_config': <function phikon_v2.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'phikon_v2'
- pathbench.models.feature_extractors.resnet50(pretrained: bool, progress: bool, key: str, **kwargs)[source]
Load the ResNet-50 model
- Parameters:
pretrained (bool) – Whether to load the pretrained weights
progress (bool) – Whether to show the download progress
key (str) – The key for the model
**kwargs – Additional keyword arguments
- Returns:
The ResNet-50 model
- Return type:
- class pathbench.models.feature_extractors.swav(tile_px=256)[source]
Bases:
TorchFeatureExtractorLunit-IO SwAV feature extractor, with ResNet-50 backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The ResNet-50 model
- Type:
ResNet50 truncated
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Lunit-IO SwAV feature extractor, with ResNet-50 backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : ResNet50 truncated\n The ResNet-50 model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'swav', '__init__': <function swav.__init__>, 'dump_config': <function swav.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'swav'
- class pathbench.models.feature_extractors.transpath_mocov3(tile_px=256)[source]
Bases:
TorchFeatureExtractorTransPath MoCoV3 feature extractor, with small Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n TransPath MoCoV3 feature extractor, with small Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'transpath_mocov3', '__init__': <function transpath_mocov3.__init__>, 'dump_config': <function transpath_mocov3.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'transpath_mocov3'
- class pathbench.models.feature_extractors.uni(tile_px=256)[source]
Bases:
TorchFeatureExtractorUNI feature extractor, with ViT-Large backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Vision Transformer model
- Type:
VisionTransformer
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n UNI feature extractor, with ViT-Large backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VisionTransformer\n The Vision Transformer model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n\n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'uni', '__init__': <function uni.__init__>, 'dump_config': <function uni.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'uni'
- class pathbench.models.feature_extractors.virchow(tile_px=256)[source]
Bases:
TorchFeatureExtractorVirchow feature extractor, with Vision Transformer backbone
- Parameters:
tile_px (int) – The size of the tile
- model
The Virchow model
- Type:
VirchowEmbedder
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Virchow feature extractor, with Vision Transformer backbone\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n\n Attributes\n ---------- \n model : VirchowEmbedder\n The Virchow model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict \n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n ', 'tag': 'virchow', '__init__': <function virchow.__init__>, 'dump_config': <function virchow.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'virchow'
- class pathbench.models.feature_extractors.virchow2(tile_px=256)[source]
Bases:
TorchFeatureExtractorVirchow2 feature extractor, with Huge Vision Transformer backbone.
- Parameters:
tile_px (int) – The size of the tile
- model
The Virchow model
- Type:
VirchowEmbedder
- transform
The transformation pipeline
- Type:
torchvision.transforms.Compose
- preprocess_kwargs
The preprocessing arguments
- Type:
dict
- __call__(obj, **kwargs)
Generate features for a batch of images or a WSI.
- __dict__ = mappingproxy({'__module__': 'pathbench.models.feature_extractors', '__doc__': '\n Virchow2 feature extractor, with Huge Vision Transformer backbone.\n\n Parameters\n ----------\n tile_px : int\n The size of the tile\n \n Attributes\n ----------\n model : VirchowEmbedder\n The Virchow model\n transform : torchvision.transforms.Compose\n The transformation pipeline\n preprocess_kwargs : dict\n The preprocessing arguments\n \n Methods\n -------\n dump_config()\n Dump the configuration of the feature extractor\n \n ', 'tag': 'virchow2', '__init__': <function virchow2.__init__>, 'dump_config': <function virchow2.dump_config>, '__annotations__': {}})
- __init__(tile_px=256)[source]
Initialize the base feature extractor.
- Parameters:
backend (str) – Either ‘tensorflow’ or ‘torch’. Used to determine which Tensor format this feature extractor can work with.
include_preds (bool) – Whether the output of this extractor also returns predictions. If so, they should be returned after the features. Defaults to False.
- __module__ = 'pathbench.models.feature_extractors'
- __str__()
Return str(self).
- __weakref__
list of weak references to the object (if defined)
- citation = ''
- cite()
Print the citation for the pretrained model in Nature format.
- dump_config()[source]
Dump the configuration of this feature extractor.
The configuration should be a dictionary of all parameters needed to re-instantiate this feature extractor. The dictionary should have the keys ‘class’ and ‘kwargs’, where ‘class’ is the name of the class, and ‘kwargs’ is a dictionary of keyword arguments.
- is_tensorflow()
- is_torch()
- license = ''
- property normalizer: StainNormalizer | None
Returns the configured whole-slide image normalizer.
- print_license() None
Print the license statement for the pretrained model.
- tag = 'virchow2'
- pathbench.models.feature_extractors.vit_small(pretrained: bool, progress: bool, key: str, **kwargs)[source]
Load the Vision Transformer model with small configuration
- Parameters:
pretrained (bool) – Whether to load the pretrained weights
progress (bool) – Whether to show the download progress
key (str) – The key for the model
**kwargs – Additional keyword arguments
- Returns:
The ViT-Small model
- Return type:
VisionTransformer